import { MigrationInterface, QueryRunner } from "typeorm";

export class AddSkuAndSpecSupport1696423001000 implements MigrationInterface {
	public async up(queryRunner: QueryRunner): Promise<void> {
		// 添加可用库存字段到商品表
		await queryRunner.query(`
            ALTER TABLE products 
            ADD COLUMN available_stock INT DEFAULT 0;
        `);

		// 更新初始可用库存等于实际库存
		await queryRunner.query(`
            UPDATE products 
            SET available_stock = stock;
        `);

		// 创建商品规格表
		await queryRunner.query(`
            CREATE TABLE product_specs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(50) NOT NULL,
                values TEXT NOT NULL,
                product_id INT NOT NULL,
                FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
            );
        `);

		// 创建商品SKU表
		await queryRunner.query(`
            CREATE TABLE product_skus (
                id INT AUTO_INCREMENT PRIMARY KEY,
                specs JSON NOT NULL,
                price INT NOT NULL,
                stock INT NOT NULL,
                available_stock INT DEFAULT 0,
                image VARCHAR(255),
                product_id INT NOT NULL,
                spec_id INT,
                FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
                FOREIGN KEY (spec_id) REFERENCES product_specs(id)
            );
        `);

		// 添加SKU字段到订单项表
		await queryRunner.query(`
            ALTER TABLE order_items 
            ADD COLUMN sku_id INT,
            ADD COLUMN sku_specs JSON,
            ADD FOREIGN KEY (sku_id) REFERENCES product_skus(id);
        `);
	}

	public async down(queryRunner: QueryRunner): Promise<void> {
		// 删除订单项表中的SKU字段
		await queryRunner.query(`
            ALTER TABLE order_items 
            DROP FOREIGN KEY \`FK_order_items_sku_id\`,
            DROP COLUMN sku_id,
            DROP COLUMN sku_specs;
        `);

		// 删除商品SKU表
		await queryRunner.query(`DROP TABLE product_skus;`);

		// 删除商品规格表
		await queryRunner.query(`DROP TABLE product_specs;`);

		// 删除商品表中的可用库存字段
		await queryRunner.query(`
            ALTER TABLE products 
            DROP COLUMN available_stock;
        `);
	}
}
